<?php

namespace Simanx\Spes\Attribute\Route\Permission;

class PermissionGroup extends Permission
{
    /**
     * 子权限
     * @var Permission|PermissionGroup[]
     */
    public array $children;

    public function __construct(string $permission, string $name = null, array $options = [], $children = [])
    {
        parent::__construct($permission, $name, $options);
        $this->children = $children;
    }

    public function addChild(Permission|PermissionGroup $child)
    {
        $this->children[$child->permission] = $child;
    }

    public function addChildren(array $children)
    {
        foreach ($children as $child) {
            $this->addChild($child);
        }
    }

    public function removeChild(Permission|PermissionGroup $child)
    {
        unset($this->children[$child->permission]);
    }

    public function hasChild(string|Permission|PermissionGroup $permission)
    {
        if ($permission instanceof Permission) {
            $permission = $permission->permission;
        }

        return isset($this->children[$permission]);
    }

    public function toArray()
    {
        $result = parent::toArray();
        $children = [];
        foreach ($this->children as $key => $child) {
            $children[$key] = $child->toArray();
        }

        $result['children'] = $children;
        return $result;
    }
}